import cv2 as cv
import threading


class CameraInput(threading.Thread):

    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self.camera = cv.VideoCapture(0)
        self.frame_buffer = None
        self.frame_buffer_lock = threading.Lock()
        self.isQuit = False

    def run(self):
        if not self.camera.isOpened():
            print('Error')
            exit()

        while not self.isQuit:
            ret, frame = self.camera.read()
            if ret:
                with self.frame_buffer_lock:
                    self.frame_buffer = frame

        self.camera.release()

    def retrieve(self):
        ret = None
        with self.frame_buffer_lock:
            ret = self.frame_buffer
        return ret

    def set_quit(self):
        self.isQuit = True
